package cn.leonis.leetcode;

/**
 * @Author Tobi
 * @Date 2021-09-11 下午2:10
 * 搜索2维矩阵2
 */
public class Search2DMatrix2Solution {

    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 4, 7, 11, 15},{2, 5, 8, 12, 19},{3, 6, 9, 16, 22},{10, 13, 14, 17, 24},{18, 21, 23, 26, 30}};
        int target = 60;
        Search2DMatrix2Solution solution = new Search2DMatrix2Solution();
        System.out.println(solution.searchMatrix1(matrix, target));
    }

    /**
     * 解法一：暴力破解法，双重循环，时间复杂度 m * n
     * @param matrix
     * @param target
     * @return
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == target) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 解法二：由于矩阵有一定的规律
     * @param matrix
     * @param target
     * @return
     */
    public boolean searchMatrix1(int[][] matrix, int target) {
        int col = matrix[0].length - 1;
        int row = 0;
        while (col >= 0 && row < matrix.length) {
            if (target == matrix[row][col]) {
                return true;
            } else if (target < matrix[row][col]) {
                col--;
            }else if (target > matrix[row][col]){
                row++;
            }
        }
        return false;
    }
}
